// pages/index.tsx
import React, { useState,useEffect } from 'react';
import { View, Button,Image,Text,setStorage,navigateTo, usePageEvent,getStorage,getLaunchOptionsSync,getAI2AgentVariableAgentVariableList,hideMenuButton,getAccountInfo } from '@ray-js/ray';
import styles from './index.module.less';
import PrimaryPieChart from '../../components/PrimaryPieChart';
import RealFlower from '../../assets/images/tab/RealFlower.png'
import BraveFlower from '../../assets/images/tab/BraveFlower.png'
import CaringFlower from '../../assets/images/tab/CaringFlower.png'
import AwareFlower from '../../assets/images/tab/AwareFlower.png'
import ActionFlower from '../../assets/images/tab/ActionFlower.png'
import FlowerImage from '../../assets/images/tab/FlowerImage.png'

export default function IndexPage() {

  //长按成长花园页面顶端居中位置5秒显示版本号
  const [VersionExist,setVersionExist]=useState(false)
  const [Version,setVersion]=useState('')
  const [pressTimer, setPressTimer] = useState(null);

  // 开始长按计时
  const startPressTimer = () => {
    const timer = setTimeout(() => {
      setVersionExist(!VersionExist)
    }, 5000); // 5秒
    setPressTimer(timer);
  };

  // 取消长按计时
  const cancelPressTimer = () => {
    if (pressTimer) {
      clearTimeout(pressTimer);
      setPressTimer(null);
    }
  };


    useEffect(()=>{
      //获取小程序版本号
      getAccountInfo({
        success: (res) => {
          setVersion(res.miniProgram.version)
        },
        fail: (error) => {
          console.log('getAccountInfo fail', error);
        }
      });
      //隐藏胶囊按钮
      hideMenuButton({  });
      //初始获取变量
      const { query: { deviceId } } = getLaunchOptionsSync();
      const FetchVariable=async()=>{
        try {
          const newVariables = await getAI2AgentVariableAgentVariableList({  
            devId: deviceId,  
          });
          const guReal = Number(newVariables.find(user => user.variableKey === 'custom.guReal')?.variableValue);
          const guBrave = Number(newVariables.find(user => user.variableKey === 'custom.guBrave')?.variableValue);
          const guLove = Number(newVariables.find(user => user.variableKey === 'custom.guLove')?.variableValue);
          const guCheck = Number(newVariables.find(user => user.variableKey === 'custom.guCheck')?.variableValue);
          const guAction = Number(newVariables.find(user => user.variableKey === 'custom.guAction')?.variableValue);
          setStorage({
            key:deviceId+'1',
            data:{
              Realvalue:guReal,
              Bravevalue:guBrave,
              Caringvalue:guLove,
              Awarevalue:guCheck,
              Actionvalue:guAction
            }
          })
        } catch (error) {
  
        }
      }

      FetchVariable();
      

      getStorage({
        key:deviceId+'1',
        success(res){
          let result1;
          let result2;
          let result3;
          let result4;
          let result5;
          //如果数据为空，设置初始数据
          if(res.data===null)
          {
            setStorage({
              key:deviceId+'1',
              data:{
                Realvalue:0,
                Bravevalue:0,
                Caringvalue:0,
                Awarevalue:0,
                Actionvalue:0
              }
            })
            result1=0;
            result2=0;
            result3=0;
            result4=0;
            result5=0;
          }
          else{
            result1=Number(res.data.Realvalue);
            result2=Number(res.data.Bravevalue);
            result3=Number(res.data.Caringvalue);
            result4=Number(res.data.Awarevalue);
            result5=Number(res.data.Actionvalue);
          }
          setRealValue(result1);
          setBraveValue(result2);
          setCaringValue(result3);
          setAwareValue(result4);
          setActionValue(result5);
        }
      })
    },[])
    const [RealValue,setRealValue]=useState(0);
    const [BraveValue,setBraveValue]=useState(0);
    const [CaringValue,setCaringValue]=useState(0);
    const [AwareValue,setAwareValue]=useState(0);
    const [ActionValue,setActionValue]=useState(0);
    useEffect(() => {       //每十秒取一次Value值
      const interval = setInterval(async() => {
        const { query: { deviceId } } = getLaunchOptionsSync();
        getStorage({
          key:deviceId+'1',
          success(res){
            const result1=Number(res.data.Realvalue);
            const result2=Number(res.data.Bravevalue);
            const result3=Number(res.data.Caringvalue);
            const result4=Number(res.data.Awarevalue);
            const result5=Number(res.data.Actionvalue);
            setRealValue(result1);
            setBraveValue(result2);
            setCaringValue(result3);
            setAwareValue(result4);
            setActionValue(result5);
          }
        })

      try {
        const newVariables = await getAI2AgentVariableAgentVariableList({  
          devId: deviceId,  
        });
        const guReal = Number(newVariables.find(user => user.variableKey === 'custom.guReal')?.variableValue);
        const guBrave = Number(newVariables.find(user => user.variableKey === 'custom.guBrave')?.variableValue);
        const guLove = Number(newVariables.find(user => user.variableKey === 'custom.guLove')?.variableValue);
        const guCheck = Number(newVariables.find(user => user.variableKey === 'custom.guCheck')?.variableValue);
        const guAction = Number(newVariables.find(user => user.variableKey === 'custom.guAction')?.variableValue);
        setStorage({
          key:deviceId+'1',
          data:{
            Realvalue:guReal,
            Bravevalue:guBrave,
            Caringvalue:guLove,
            Awarevalue:guCheck,
            Actionvalue:guAction
          }
        })
      } catch (error) {

      }
      }, 2000); // 间隔 10000ms（10秒）
  
      return () => clearInterval(interval); // 组件卸载时清理定时器
    }, []);

    const OpenRealFlower=()=>{

        getStorage({
          key:'FlowerExist',
          success(res){
            setStorage({
              key:'FlowerExist',
              data:{
                ...res.data,
                RealFlower:true
              }
            })
          }
        })
        
          navigateTo({ 
            url:'/pages/GrowDetail/index',
           })
    }
    const OpenBraveFlower=()=>{

      getStorage({
        key:'FlowerExist',
        success(res){
          setStorage({
            key:'FlowerExist',
            data:{
              ...res.data,
              BraveFlower:true
            }
          })
        }
      })
        
          navigateTo({ 
            url:'/pages/GrowDetail/index',
           })
    }
    const OpenCaringFlower=()=>{

      getStorage({
        key:'FlowerExist',
        success(res){
          setStorage({
            key:'FlowerExist',
            data:{
              ...res.data,
              CaringFlower:true
            }
          })
        }
      })
        
          navigateTo({ 
            url:'/pages/GrowDetail/index',
           })
    }
    const OpenAwareFlower=()=>{

      getStorage({
        key:'FlowerExist',
        success(res){
          setStorage({
            key:'FlowerExist',
            data:{
              ...res.data,
              AwareFlower:true
            }
          })
        }
      })
        
          navigateTo({ 
            url:'/pages/GrowDetail/index',
           })
    }
    const OpenActionFlower=()=>{

      getStorage({
        key:'FlowerExist',
        success(res){
          setStorage({
            key:'FlowerExist',
            data:{
              ...res.data,
              ActionFlower:true
            }
          })
        }
      })
        
          navigateTo({ 
            url:'/pages/GrowDetail/index',
           })
    }

  
  return(
    <>
      <View className={styles.bgimg}>
        <View className={styles.primarypiechart}>
            <PrimaryPieChart value1={RealValue}
                             value2={BraveValue}
                             value3={CaringValue}
                             value4={AwareValue}
                             value5={ActionValue}>
                             </PrimaryPieChart>
        </View>

        <View className={styles.FlowerContainer}>

            <View className={styles.box} onClick={OpenRealFlower} style={{backgroundColor:'#d4e2f8'}}>
                <Button className={styles.FlowerBtn}>
                    <Image className={styles.FlowerImg} src={RealFlower}></Image>
                </Button>
                <Text className={styles.FlowerName}>真实之花</Text>
                <Text className={styles.FlowerContent}>在你接纳真实自己时绽放</Text>
            </View>

            <View className={styles.box} onClick={OpenBraveFlower} style={{backgroundColor:'#ebdae7'}}>
                <Button className={styles.FlowerBtn}>
                    <Image className={styles.FlowerImg} src={BraveFlower}></Image>
                </Button>
                <Text className={styles.FlowerName}>勇敢之花</Text>
                <Text className={styles.FlowerContent}>在你面对恐惧,勇敢迈出第一步时绽放</Text>
            </View>

            <View className={styles.box} onClick={OpenCaringFlower} style={{backgroundColor:'#d2e8ee'}}>
                <Button className={styles.FlowerBtn}>
                    <Image className={styles.FlowerImg} src={CaringFlower}></Image>
                </Button>
                <Text className={styles.FlowerName}>关怀之花</Text>
                <Text className={styles.FlowerContent}>在你照顾好自己、关爱他人时绽放</Text>
            </View>

            <View className={styles.box} onClick={OpenAwareFlower} style={{backgroundColor:'#dadef9'}}>
                <Button className={styles.FlowerBtn}>
                    <Image className={styles.FlowerImg} src={AwareFlower}></Image>
                </Button>
                <Text className={styles.FlowerName}>觉知之花</Text>
                <Text className={styles.FlowerContent}>在你自我觉察时绽放</Text>
            </View>

            <View className={styles.box} onClick={OpenActionFlower} style={{backgroundColor:'#ebe2dd'}}>
                <Button className={styles.FlowerBtn}>
                    <Image className={styles.FlowerImg} src={ActionFlower}></Image>
                </Button>
                <Text className={styles.FlowerName}>行动之花</Text>
                <Text className={styles.FlowerContent}>在你完成积极行动时绽放</Text>
            </View>
        </View>

        <View className={styles.touch} style={{left:'42%',top:'11%'}} onClick={OpenRealFlower}></View>
        <View className={styles.touch} style={{left:'61%',top:'18%'}} onClick={OpenBraveFlower}></View>
        <View className={styles.touch} style={{left:'52%',top:'29%'}} onClick={OpenCaringFlower}></View>
        <View className={styles.touch} style={{left:'32%',top:'29%'}} onClick={OpenAwareFlower}></View>
        <View className={styles.touch} style={{left:'24%',top:'18%'}} onClick={OpenActionFlower}></View>

        {VersionExist &&
            <Text className={styles.version}>版本号:{Version}</Text>
        }

        <View className={styles.CheckVersion} onTouchStart={startPressTimer} onTouchEnd={cancelPressTimer} onTouchCancel={cancelPressTimer}></View>
      </View>
    </>
  );
}